import { RoleService } from 'src/app/@core/services/role/role.service';
import { Component, OnInit, Renderer2 } from '@angular/core';
import { DialogService } from 'ng-devui/modal';
import { DrawerService } from 'ng-devui/drawer';
import { Subject } from 'rxjs';
import { SideSettingsComponent } from '../@shared/components/side-settings/side-settings.component';
import { PersonalizeComponent } from '../@shared/components/personalize/personalize.component';
import { PersonalizeService } from '../@core/services/personalize.service';
import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core';
import { DaLayoutConfig, DaLayoutService } from '../@shared/layouts/da-layout';
import getMenu from './menu';
import { DaScreenMediaQueryService } from '../@shared/layouts/da-grid';
import { takeUntil } from 'rxjs/operators';
import { SideMenuComponent } from '../@shared/components/side-menu/side-menu.component';
import { Theme } from 'ng-devui/theme';
import {
  animate,
  state,
  style,
  transition,
  trigger,
} from '@angular/animations';
import { MenuService } from '../@core/services/menu/menu.service';
import menuData from '../@core/data/menu.json';
import { GetCodeService } from '../@core/services/getCode/get-code.service';
@Component({
  selector: 'da-pages',
  templateUrl: './pages.component.html',
  styleUrls: ['./pages.component.scss'],
  animations: [
    trigger('fadeInOut', [
      state('in', style({ opacity: 1, transform: 'translateX(0)' })),
      transition(':enter', [
        style({ opacity: 0, transform: 'translateX(-10px)' }),
        animate('300ms ease-out'),
      ]),
      transition(':leave', [
        animate(
          '300ms ease-in',
          style({ opacity: 0, transform: 'translateX(-20px)' })
        ),
      ]),
    ]),
  ],
})
export class PagesComponent implements OnInit {
  private destroy$ = new Subject<void>();
  menu: any;
  roles: any;
  layoutConfig: DaLayoutConfig = { id: 'sidebar', sidebar: {} };
  isSidebarShrink: boolean = false;
  isSidebarFold: boolean = false;
  settingDrawer: any;
  FifterMenu: any = [];
  codeData: any;
  link: any;
  code: any;
  constructor(
    private drawerService: DrawerService,
    private dialogService: DialogService,
    private personalizeService: PersonalizeService,
    private layoutService: DaLayoutService,
    private translate: TranslateService,
    private mediaQueryService: DaScreenMediaQueryService,
    private render2: Renderer2,
    private RoleService: RoleService,
    private menuService: MenuService,
    private getCodeService: GetCodeService
  ) {
    this.personalizeService.initTheme();
    this.layoutService
      .getLayoutConfig()
      .pipe(takeUntil(this.destroy$))
      .subscribe((config: DaLayoutConfig) => {
        this.layoutConfig = config;
        this.isSidebarShrink = !!this.layoutConfig.sidebar.shrink;
      });
    this.mediaQueryService
      .getPoint()
      .pipe(takeUntil(this.destroy$))
      .subscribe(({ currentPoint, change, compare }) => {
        if (change <= 0 && compare['ml'] <= 0) {
          this.sidebarShrink(true);
        } else if (change >= 0 && compare['ml'] > 0) {
          this.sidebarShrink(false);
        }
        if (change <= 0 && compare['mm'] <= 0) {
          this.sidebarFold(true);
        } else if (change >= 0 && compare['mm'] > 0) {
          this.sidebarFold(false);
        }
      });
    }
  ngOnInit() {

    this.translate
      .get('page')
      .pipe(takeUntil(this.destroy$))
      .subscribe((res) => {
        this.updateMenu(res);
      });
    this.translate.onLangChange
      .pipe(takeUntil(this.destroy$))
      .subscribe((event: TranslationChangeEvent) => {
        const values = this.translate.instant('page');
        this.updateMenu(values);
      });
    let userinfo = localStorage.getItem('userinfo');
    if (!userinfo) {
      userinfo = sessionStorage.getItem('userinfo');
    }
    if (userinfo) {
      const parsedUserinfo = JSON.parse(userinfo);
      const roles = parsedUserinfo.roles;
      this.roles = roles.map((item: { roleId: any }) => item.roleId);
    }
    let results = [];
    this.menuService.GetMenusByRole(this.roles).subscribe((data: any) => {
      // this.FifterMenu = this.getIntersection(menuData, data);+
      // this.FifterMenu.forEach((item: any) =>
      //   this.removeEmptyChildrenMenu(item)
      // );
      this.FifterMenu = menuData;
      this.FifterMenu.forEach((item: any) =>
        this.removeEmptyChildrenMenu(item)
      );
      this.menuService.setMenuItems(data);
    });
    this.personalizeService.getUiTheme()!.subscribe((theme) => {
      const currentTheme = Object.values(
        (window as { [key: string]: any })['devuiThemes']
      ).find((i: Theme | unknown) => {
        return (i as Theme).id === theme;
      });
      if (currentTheme && (<any>currentTheme).isDark) {
        this.render2.addClass(document.body, 'is-dark');
      } else {
        this.render2.removeClass(document.body, 'is-dark');
      }
    });
    const appKey = 'Yo8wliRq';
    const secretKey = '43cd8cbc2284593e1af039f53496413c5e185204';

    this.getCodeService.getCode().subscribe({
      next: (res:any) => {
        this.codeData = res;
        console.log('获取 CODE 返回：', res);
        this.link = res.data.link
        this.code = res.data.code
      },
      error: (err) => {
        console.error('请求失败：', err);
      }
    })
  }
  getIntersection(arr1: any[], arr2: any[]): any[] {
    const result: any[] = []
    const findIntersection = (items1: any[], items2: any[]): any[] => {
      const intersection: any[] = [];
      for (const item1 of items1) {
        for (const item2 of items2) {
          if (item1.id === item2.id) {
            const newItem = { ...item1 };
            if (
              item1.childrenMenu &&
              item1.childrenMenu.length > 0 &&
              item2.childrenMenu &&
              item2.childrenMenu.length > 0
            ) {
              newItem.childrenMenu = findIntersection(
                item1.childrenMenu,
                item2.childrenMenu
              );
            }
            intersection.push(newItem);
          }
        }
      }
      return intersection;
    };
    return findIntersection(arr1, arr2);
  }
  removeEmptyChildrenMenu(menuItem: any): void {
    if (menuItem.childrenMenu && menuItem.childrenMenu.length === 0) {
      delete menuItem.childrenMenu;
    } else if (menuItem.childrenMenu) {
      menuItem.childrenMenu.forEach((child: any) =>
        this.removeEmptyChildrenMenu(child)
      );
    }
  }
  updateMenu(values: any) {
    this.menu = getMenu(values);
  }
  filterDataByTitles(data: any[], titles: string[]): any[] {
    function filterChildren(children: any[]): any[] {
      return children
        .map((child) => {
          if (child.children) {
            return {
              ...child,
              children: filterChildren(child.children),
            };
          }
          return child;
        })
        .filter(
          (child) =>
            titles.includes(child.title) ||
            (child.children && child.children.length > 0)
        );
    }

    return data
      .map((item) => {
        if (item.children) {
          return {
            ...item,
            children: filterChildren(item.children),
          };
        }
        return item;
      })
      .filter((item) => item.children && item.children.length > 0);
  }
  openSideMenuDrawer() {
    this.drawerService.open({
      drawerContentComponent: SideMenuComponent,
      width: '240px',
      position: 'left',
      data: {
        data: this.menu,
      },
    });
  }
  openSettingDrawer() {
    if (this.settingDrawer) {
      this.settingDrawer.drawerInstance.show();
    } else {
      this.settingDrawer = this.drawerService.open({
        drawerContentComponent: SideSettingsComponent,
        width: '350px',
        destroyOnHide: false,
        data: {
          close: () => {
            this.settingDrawer.drawerInstance.hide();
          },
        },
      });
    }
  }
  personalizeConfig() {
    this.dialogService.open({
      id: 'theme',
      width: '800px',
      maxHeight: '800px',
      title: '',
      content: PersonalizeComponent,
      backdropCloseable: true,
      draggable: false,
      onClose: () => {},
      buttons: [],
    });
  }
  sidebarShrink(isShrink: boolean) {
    this.isSidebarShrink = isShrink;
    if (this.layoutConfig.sidebar.firSidebar) {
      this.layoutConfig.sidebar.firSidebar.width = this.isSidebarShrink
        ? 54
        : 240;
    }
    this.layoutConfig.sidebar.shrink = this.isSidebarShrink;
    this.layoutService.updateLayoutConfig(this.layoutConfig);
  }
  sidebarFold(isFold: boolean) {
    this.isSidebarFold = isFold;
    if (this.layoutConfig.sidebar.firSidebar) {
      this.layoutConfig.sidebar.firSidebar.hidden = isFold;
      this.layoutService.updateLayoutConfig(this.layoutConfig);
    }
  }
  destroy() {
    this.destroy$.next();
    this.destroy$.complete();
    this.settingDrawer.drawerInstance.destroy();
    this.settingDrawer = null;
  }
  childeMenu: any = {
    title: '',
    childeMenu: [],
  };
  clideMenuDisplay: boolean = false;
  handkeItemHover(item: any) {
    this.childeMenu = item;
    this.clideMenuDisplay = true;
  }
  handkeItemHoverOut() {
    this.clideMenuDisplay = false;
  }
  topChildMenu: boolean = false;
  handleTopItemHover(item: any) {
    this.topChildMenu = true;
    this.childeMenu = item;
  }
  topChildMenuOut() {
    this.topChildMenu = false;
  }
  init(p) {
    // 初始化 一般在页面挂载时候初始化，下面demo为了调整参数不同，放在了点击事件中
    window.xiaoe.init({
        // 从小e开放平台获取到的link 以下为示例链接
        link: this.link+'?code='+this.code,
        // 显示终端类型pc mobile 默认为pc
        type: 'pc',
        // 弹框的宽度 数值 默认720
        width: 720,
        // 弹框的高度 数值 默认600
        height: 600,
        // 点击客服外部是否关闭 默认false
        clickAway: true,
        // 弹框的类名
        className: '',
        // 触发器 默认false
        trigger: false,
        // 弹框的位置 数值  默认 null 屏幕居中
        /**
         *  position: {
                left?: number;
                top?: number;
                right?: number;
                bottom?: number;
            }
        */
        position: null,
        // 关闭是否销毁 默认false
        closeDestory: false,
        // 是否显示全屏按钮 暂只支持pc 默认false
        showFullScreen: true,
        // 关闭是否自动退出全屏 closeDestory为false 的情况有效
        closeExitFullScreen: true,
        ...p,
    });
  }
  openAi(){
    this.getCodeService.getCode().subscribe({
      next: (res:any) => {
        this.codeData = res;
        console.log('获取 CODE 返回：', res);
        this.link = res.data.link
        this.code = res.data.code
        setTimeout(() => {
          this.init({
              type: 'mobile',
              direction: 'right',
              // closeDestory: true,
              width: 500,
              trigger: true,
          });
          window.xiaoe.open();
      }, 500);
      },
      error: (err) => {
        console.error('请求失败：', err);
      }
    })

  }
}
